﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoYuan.Framework.Uitility
{
    public class TxtHelper
    {
        /// <summary>
        /// 覆盖内容写入txt
        /// </summary>
        /// <param name="path">txt物理路径</param>
        /// <param name="content">内容</param>
        public static void WriteTxt(string path, string content)
        {
            File.WriteAllText(path, content, Encoding.UTF8);
        }

        /// <summary>
        /// 追加到末尾写入txt
        /// </summary>
        /// <param name="path">txt物理路径</param>
        /// <param name="content">内容</param>
        public static void WriteTxtAppend(string path, string content)
        {
            //File.AppendAllText 方法会自动创建文件，但是不判断路径是否存在
            File.AppendAllText(path, content, Encoding.UTF8);
        }

        /// <summary>
        /// 读取txt内容
        /// </summary>
        /// <param name="path">txt物理路径(如果文件不存在 则返回为null)</param>
        /// <returns></returns>
        public static string ReadTxt(string path)
        {
            try
            {
                StreamReader sr = new StreamReader(path, Encoding.UTF8);
                StringBuilder sb = new StringBuilder();
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line.ToString());
                }
                sr.Close();
                sr.Dispose();
                return sb.ToString();
            }
            catch (IOException e)
            {
                //Console.WriteLine(e.ToString());
                return null;
            }
        }

    }
}
